import Vue from 'vue'
import VueRouter from 'vue-router'

import Layout from '@/views/layout'
import Login from '@/views/login'
import Dashboard from '@/views/dashboard'
import Article from '@/views/article'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  // 一级路由
  { path: '/login', component: Login },
  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [
      // 二级路由
      { path: 'dashboard', component: Dashboard },
      { path: 'article', component: Article }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 全局前置导航守卫:登录拦截
// to: 要去的路由对象
// from: 从哪儿来的路由对象
// next: 是否放行和拦截
router.beforeEach((to, from, next) => {
  const { token } = store.state.user
  // 核心逻辑: 只对登录用户开放，如果未登录，一律拦截到登录页
  // 如果访问的不是登录页，且无token，一律拦截到登录页
  if (to.path !== '/login' && !token) return next('/login')
  // 如果访问的是登录页，或者访问的是首页且带有token
  next()
})

export default router
